//
//  OrderCourseViewController.m
//  test
//
//  Created by 朱圳 on 2017/12/22.
//  Copyright © 2017年 朱圳. All rights reserved.
//
#define kViolet [UIColor colorWithRed:170/255.0 green:114/255.0 blue:219/255.0 alpha:1.0]
#define themeColor  [UIColor colorWithRed:235/255.0f green:91/255.0f blue:87/255.0f alpha:1]

#import "OrderCourseViewController.h"

#import "FSCalendar.h"
#import "QFTimePickerView.h"
#import "OrderModel.h"

@interface OrderCourseViewController ()<FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance>
@property (weak, nonatomic) FSCalendar *calendar;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;
@property (strong, nonatomic) NSDictionary *fillDefaultColors;
@property (strong, nonatomic) UIButton *startTimeBtn;
@property (strong, nonatomic) UIButton *endTimeBtn;
@property (strong, nonatomic) NSString *yDate;
@end

@implementation OrderCourseViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dateFormatter = [[NSDateFormatter alloc] init];
        self.dateFormatter.dateFormat = @"yyyyMMdd";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self SendLessonUI];
    [self ChooseTimeUI];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.calendar.accessibilityIdentifier = @"calendar";
    self.yDate = [self.dateFormatter stringFromDate:[NSDate date]];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.endTimeBtn setTitle:@"结束时间" forState:UIControlStateNormal];
    [self.startTimeBtn setTitle:@"开始时间" forState:UIControlStateNormal];
}
- (void)loadView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.view = view;
    //日历的背景
    UIImageView *calendarBack = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"日历"]];
    calendarBack.frame = CGRectMake(20, Navigation_Bar_Height+10, ScreenWidth-40,ScreenHeight/2+10);
    [self.view addSubview:calendarBack];
    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(25, Navigation_Bar_Height+15, ScreenWidth-50, ScreenHeight/2)];
    calendar.dataSource = self;
    calendar.delegate = self;
    //允许多选,可以选中多个日期
    calendar.allowsMultipleSelection = NO;
    calendar.swipeToChooseGesture.enabled = YES;
    calendar.placeholderType = FSCalendarPlaceholderTypeNone;
    calendar.backgroundColor = [UIColor clearColor];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文
    calendar.locale = locale;  // 设置周次是中文显示
    calendar.appearance.caseOptions = FSCalendarCaseOptionsWeekdayUsesSingleUpperCase|FSCalendarCaseOptionsHeaderUsesUpperCase;;//中文
    calendar.appearance.headerDateFormat = @"yyyy年MM月";
    calendar.appearance.borderRadius = 1;//圆形
    //设置字体大小\颜色
    calendar.appearance.subtitleFont = [UIFont systemFontOfSize:8];
    calendar.appearance.headerTitleColor = [UIColor whiteColor];
    calendar.appearance.weekdayTextColor = [UIColor whiteColor];
    calendar.appearance.selectionColor = [UIColor orangeColor];
    //日历头部颜色
    calendar.calendarHeaderView.backgroundColor = themeColor;
    calendar.calendarWeekdayView.backgroundColor = themeColor;
    //隐藏上下月的透明度
    calendar.appearance.headerMinimumDissolvedAlpha = 0;
    [self.view addSubview:calendar];
    self.calendar = calendar;
}

-(void)ChooseTimeUI{
    UIView *backview1=[[UIView alloc]initWithFrame:CGRectMake(20,(Navigation_Bar_Height+10+(ScreenHeight/2+10))+10, ScreenWidth-50, 50)];
    backview1.backgroundColor = [UIColor clearColor];
    UILabel *chooseleb=[[UILabel alloc]initWithFrame:CGRectMake(8, 10, 140, 30)];
    chooseleb.text=@"上课时间:";
    chooseleb.textAlignment=NSTextAlignmentLeft;
    chooseleb.textColor=[UIColor blackColor];
    chooseleb.font=[UIFont systemFontOfSize:16];
    
    UIButton *startTime=[[UIButton alloc]initWithFrame:CGRectMake(80, 10,80, 30)];
    [startTime setTitle:@"开始时间" forState:UIControlStateNormal];
    startTime.tag = 1;
    [startTime setBackgroundColor:dominantColor];
    [startTime setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    startTime.titleLabel.font=[UIFont systemFontOfSize:14];
    [startTime addTarget:self action:@selector(sendBtnAction:) forControlEvents:UIControlEventTouchDown];
    self.startTimeBtn = startTime;
    
    UIButton *endTime=[[UIButton alloc]initWithFrame:CGRectMake(160, 10,80, 30)];
    [endTime setTitle:@"结束时间" forState:UIControlStateNormal];
    endTime.tag = 2;
    [endTime setBackgroundColor:dominantColor];
    [endTime setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    endTime.titleLabel.font=[UIFont systemFontOfSize:14];
    [endTime addTarget:self action:@selector(sendBtnAction:) forControlEvents:UIControlEventTouchDown];
    self.endTimeBtn = endTime;
    [backview1 addSubview:chooseleb];
    [backview1 addSubview:startTime];
    [backview1 addSubview:endTime];
    [self.view addSubview:backview1];
}
-(void)SendLessonUI{
    //发送约课按钮背景View
    UIView *backview=[[UIView alloc]initWithFrame:CGRectMake(20, (Navigation_Bar_Height+10+(ScreenHeight/2+10))+10+60, ScreenWidth-50, 50)];
    backview.backgroundColor = [UIColor clearColor];
    UIButton *sendBtn=[[UIButton alloc]initWithFrame:CGRectMake(40, 10, ScreenWidth-130, 30)];
    sendBtn.tag = 3;
    [sendBtn setTitle:@"发送约课" forState:UIControlStateNormal];
    [sendBtn setBackgroundColor:dominantColor];
    [sendBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sendBtn.titleLabel.font=[UIFont systemFontOfSize:17];
    //设置圆角
    sendBtn.layer.cornerRadius=5;
    [sendBtn addTarget:self action:@selector(sendBtnAction:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:backview];
    [backview addSubview:sendBtn];
}
- (void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
}
#pragma mark - 发送约课
-(void)sendBtnAction:(UIButton *)sender{
    switch (sender.tag) {
        case 1:
        { NSLog(@"开始时间");
            QFTimePickerView *pickerView = [[QFTimePickerView alloc]initDatePackerWithStartHour:@"08" endHour:@"24" period:15 response:^(NSString *str) {
                [self.startTimeBtn setTitle:str forState:UIControlStateNormal];
            }];
            [pickerView show];
            
        }
            break;
        case 2:
        { NSLog(@"结束时间");
            QFTimePickerView *pickerView = [[QFTimePickerView alloc]initDatePackerWithStartHour:@"08" endHour:@"24" period:15 response:^(NSString *str) {
                [self.endTimeBtn setTitle:str forState:UIControlStateNormal];
            }];
            [pickerView show];
        }
            break;
        case 3:
        {
            NSLog(@"发送约课");
            if ([self.startTimeBtn.titleLabel.text isEqualToString:@"开始时间"]) {
                [Utility showFail:@"请选择开始时间"];
            }else{
                if ([self.endTimeBtn.titleLabel.text isEqualToString:@"结束时间"]){
                    [Utility showFail:@"请选择结束时间"];
                }else{
                    [self sendData];
                }
            }
            
        }
            break;
        default:
            break;
    }
}
#pragma mark - 发送约课
-(void)sendData{
    NSString *pname = [[NSUserDefaults standardUserDefaults] objectForKey:@"pname"];
    NSLog(@">a>%@", pname);

    if ([pname isEqualToString:@""] || pname == nil || [pname isEqual:[NSNull null]]) {
        [Utility showFail:@"约课失败!请联系教务老师或班主任!"];
    }else{
        NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
        NSTimeInterval time=[date timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
        
        NSString *startTime = [NSString stringWithFormat:@"%@  %@",self.yDate,self.startTimeBtn.titleLabel.text];
        NSString *endTime = [NSString stringWithFormat:@"%@  %@",self.yDate,self.endTimeBtn.titleLabel.text];
        NSString * start = [Utility getTimeStrWithString:startTime];
        NSString * end = [Utility getTimeStrWithString:endTime];
        //转成doubleValue数值比较
        if ([start doubleValue] <[end doubleValue]) {
            if ([start doubleValue] > [timeString doubleValue]) {
                NSDictionary *dict = @{
                                       @"sid" : Sid,
                                       @"spass" : Spassword,
                                       @"starttime":start,
                                       @"endtime":end,
                                       @"datetime":self.yDate,
                                       };
                [[AFNetworkTool shareManager]postJSONWithUrl:Studen_Order parmas:dict successData:^(id json) {
                    //          NSLog(@">>>>>>%@", json);
                    [Utility showSuccess:json[@"message"]];
                } failure:^(NSError *error) {
                    //         NSLog(@"%@",error);
                    [Utility showFail:@"网络错误"];
                }];
                
            }else{
                [Utility showFail:@"当前时间大于约课时间"];
            }
        }else{
            [Utility showFail:@"开始时间必须小于结束时间"];
        }
    }
   
}

#pragma mark - <FSCalendarDataSource>

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    self.yDate = [self.dateFormatter stringFromDate:date];
    _calendar.appearance.todayColor = [UIColor clearColor];
    _calendar.appearance.titleTodayColor = [UIColor darkTextColor];
}

//设置最小日期

- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar

{
    
    return [NSDate date];
    
}

//最大

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar

{
    NSCalendar *calender = [NSCalendar currentCalendar];
    // 设置属性，因为我只需要年,月,日，这个属性还可以支持时，分，秒
    NSDateComponents *cmp = [calender components:(NSCalendarUnitMonth | NSCalendarUnitYear|NSCalendarUnitDay) fromDate:[[NSDate alloc] init]];
    //设置上个月，即在现有的基础上减去一个月(2017年1月 减去一个月 会得到2016年12月)
    // [cmp setMonth:[cmp month] + 1];
    [cmp setDay:[cmp day] + 30];
    //拿到上个月的NSDate，再用NSDateFormatter就可以拿到单独的年和月了。
    NSDate *lastMonDate = [calender dateFromComponents:cmp];
    return lastMonDate;
    
}

#pragma mark - <FSCalendarDelegateAppearance>
- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance fillDefaultColorForDate:(NSDate *)date
{
    NSString *key = [self.dateFormatter stringFromDate:date];
    if ([_fillDefaultColors.allKeys containsObject:key]) {
        return _fillDefaultColors[key];
    }
    return nil;
}


@end
